package net.zjitc.redis;

import org.apache.ibatis.cache.Cache;


import org.apache.log4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;


import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;


/**
 * @Author admin
 * @Date 2019/5/21 8:31
 */

//readis作为mybaits的二级二级缓存
public class RedisCache implements Cache {
    /*日志*/
    private static final Logger logger = (Logger) LoggerFactory.getLogger(RedisCache.class);

    private static JedisConnectionFactory jedisConnectionFactory;
    /*标记此缓存为哪个mapper使用*/
    private final String id;
    /*多线程时，线程安全问题*/
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    /**
     * /**
     * The {@code ReadWriteLock}.
     *
     */
    public RedisCache(final String id){
        if (id == null){
            throw new IllegalArgumentException("cache instance require an ID");
        }
        logger.debug("RedisCache by zhaojingjing id = "+ id );
        this.id = id;
    }
    @Override
    public String getId() {
        return this.id;
    }

    @Override
    public void putObject(Object key, Object value) {
        JedisConnection connection = null;
        try {
            connection = jedisConnectionFactory.getConnection();
            RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
            System.out.println("key = ***"+serializer.serialize(key).toString());
            System.out.println("value = ***"+serializer.serialize(value).toString());
            connection.set(serializer.serialize(key),serializer.serialize(value));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (connection != null){
                connection.close();
            }
        }
    }

    @Override
    public Object getObject(Object key) {
        Object result = null;
        JedisConnection connection = null;
        try{
            connection = jedisConnectionFactory.getConnection();
            RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
            result = serializer.deserialize(connection.get(serializer.serialize(key)));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (connection != null){
                connection.close();
            }
        }
        return result;
    }

    @Override
    public Object removeObject(Object key) {
        JedisConnection connection = null;
        Object result = null;
        try{
            connection = jedisConnectionFactory.getConnection();
            RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
            result = connection.expireAt(serializer.serialize(key),0);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (connection != null){
                connection.close();
            }
        }
        return result;
    }

    @Override
    public void clear() {
        JedisConnection connection = null;
        try{
            connection = jedisConnectionFactory.getConnection();
            connection.flushDb();
            connection.flushAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(connection != null){
                connection.close();
            }
        }
    }

    @Override
    public int getSize() {
        int result = 0;
        JedisConnection connection = null;
        try{
            connection = jedisConnectionFactory.getConnection();
            result = Integer.valueOf(connection.dbSize().toString());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(connection != null){
                connection.close();
            }
        }
        return 0;
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return this.readWriteLock;
    }

    /*静态方法，用于注入jedisConnectionfactory*/
    public static void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory){
        RedisCache.jedisConnectionFactory = jedisConnectionFactory;
    }

}
